package com.word.app.config.token;

import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        
        // Set whiteList = new LinkedHashSet<String>();
        // whiteList.add("/login");
        // whiteList.add("/noauth");

        // if(whiteList.contains(((HttpServletRequest) request).getRequestURI())){
        //     return true;
        // }
        // if(executeLogin(request, response))
        //     return true;
        // else{
        //     JWTErrorResp.restError((HttpServletResponse)response);
        //     return false;
        // }
        return executeLogin(request, response);


        // 不检查token
        // getSubject(request, response).login(new JWTToken("token"));
        // return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");
        if(!JWTUtil.verify(token)){
            return false;
        }
            
        try {
            JWTToken jwtToken = new JWTToken(token);
            getSubject(request, response).login(jwtToken);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    // @Override
    // protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
    //     log.debug("Authentication required: sending 401 Authentication challenge response.");
    //     HttpServletResponse httpResponse = WebUtils.toHttp(response);
    //     httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
    //     httpResponse.setCharacterEncoding("utf-8");
    //     httpResponse.setContentType("application/json; charset=utf-8");
    //     final String message = "未认证，请在前端系统进行认证";
    //     try (PrintWriter out = httpResponse.getWriter()) {
    //         FebsResponse tandemResponse=new FebsResponse().message(Code.C401.getDesc()).code(Code.C401.getCode().toString()).status(ResponseStat.ERROR.getText());
    //         String json = SpringContextUtil.getBean("jacksonObjectMapper",ObjectMapper.class).writeValueAsString(tandemResponse);
    //         System.out.println(json);
    //         out.print(json);
    //     } catch (IOException e) {
    //         log.error("sendChallenge error：", e);
    //     }
    //     return false;
    // }
}
